#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <semaphore.h>
sem_t sem_1,sem_2;//声明两个全局变量，信号量，一个用于互斥，一个用于同步
void * pthread_1(void *num)
{
    int *n=(int*)num;
    sem_wait(&sem_1);//获取锁
    for(int i=0;i<5000;i++)
    {
        *n=*n+1;
        printf("in pthread_1,the num is %d\n",*n);
    }
    sem_post(&sem_1);//释放锁
    sem_post(&sem_2);//释放资源，实现同步
}
void * pthread_2(void *num)
{
    int *n=(int*)num;
    sem_wait(&sem_2);//等待获取资源
    sem_wait(&sem_1);//获取锁
    for(int i=0;i<5000;i++)
    {
        *n=*n-1;
        printf("in pthread_2,the num is %d\n",*n);
    }
    sem_post(&sem_1);//释放锁
}
int main(int argc, char *argv[])
{
    int num=0;//在进程中赋初值
    pthread_t thread_1,thread_2;//声明两个线程
    //pshared=0，表示用于进程内所有线程共享
    sem_init(&sem_1,0,1);//互斥
    sem_init(&sem_2,0,0);//同步
    pthread_create(&thread_1,NULL,pthread_1,&num);
    pthread_create(&thread_2,NULL,pthread_2,&num);
    pthread_join(thread_1,NULL);
    pthread_join(thread_2,NULL);
    return 0;
}

